﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;

    /// <summary>
    /// json格式返回数据高亮解析器
    /// </summary>
    public class JsonHighlightingParser : ISolrResponseParser<string, IDictionary<string, IDictionary<string, IList<string>>>>
    {
        public IDictionary<string, IDictionary<string, IList<string>>> Parse(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }

            var bytes = Encoding.UTF8.GetBytes(result);

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max))
            {
                var xmlDoc = XDocument.Load(reader);

                var highlighting = xmlDoc.Root.Element("highlighting");

                if (highlighting == null)
                {
                    return null;
                }

                var hlResult = highlighting.Elements("{item}item");
                var highlightingResult = new Dictionary<string, IDictionary<string, IList<string>>>(hlResult.Count());

                foreach (var hlElement in hlResult)
                {
                    var itemName = hlElement.Attribute("item").Value;
                    var itemList = hlElement.Elements("name");

                    if (!highlightingResult.ContainsKey(itemName))
                    {
                        highlightingResult[itemName] = new Dictionary<string, IList<string>>(itemList.Count());
                    }

                    foreach (var itemElement in itemList)
                    {
                        var hlItemName = itemElement.Name.LocalName;

                        if (!highlightingResult[itemName].ContainsKey(hlItemName))
                        {
                            highlightingResult[itemName][hlItemName] = new List<string>();
                        }

                        highlightingResult[itemName][hlItemName] = (from e in itemElement.Elements("item")
                                                                    select e.Value).ToList<string>();
                    }
                }

                return highlightingResult;

            }
        }
    }
}
